import React, {Component} from 'react'
import axios from 'axios'
import LineChart from '../components/LineChart'
import LadarChart from '../components/LadarChart'
import Box from '../components/Box'
import InfoList from '../components/InfoList'
import './index.css'

class PageHome extends Component {

    filters = [
        {
            label: 'cpu占用率',
            name: 'cpuPercent',
            type: 'array'
        },
        {
            label: 'cpu占用率平均值',
            name: 'cpuPercent',
            type: 'average'
        },
        {
            label: '虚拟内存占用',
            name: 'virtualMemoryPercent'
        },
        {
            label: '交换内存占用',
            name: 'swapPercent'
        },
        {
            label: '出站字节',
            name: 'networkSentBytes'
        },
        {
            label: '进站字节',
            name: 'networkRecvBytes'
        },
        {
            label: '读字节',
            name: 'diskReadBytes'
        },
        {
            label: '写字节',
            name: 'diskWriteBytes'
        },
    ]

    constructor() {
        super(...arguments)

        this.part = 2
        this.jobIdIndex = 0
        this.state = {
            selectFilterIndex: 0,
            selectType: 0,
            jobIds: [],
            chartData: {}
        }
    }

    componentDidMount() {
        // 拉取图表数据
        this.fetchJobIds().then(this.fetchLineChartData.bind(this))
    }


    // echart 文档 https://echarts.baidu.com/
    async fetchJobIds() {
        const params = {}
        // 请求接口获取图表数据
        // const response = await axios.get('/job/getAllJobId', {params})
        const response = await axios.get('https://www.easy-mock.com/mock/5ca9efd1646ec411e7a920cc/one_test/fetchJobIds', {params})

        // response.data 是接口返回的json数据（已自动转换为json对象）
        const {status, data: jobIds} = response.data

        if (status === 0) {
            await new Promise(resolve => this.setState({
                jobIds
            }, resolve))
        }
    }

    // echart 文档 https://echarts.baidu.com/
    async fetchLineChartData() {
        const {jobIds} = this.state
        const params = {
            part: this.part,
            jobId: jobIds[this.jobIdIndex]
        }
        // 请求接口获取图表数据
        // const response = await axios.get('/job/ratio', {params})
        const response = await axios.get('https://www.easy-mock.com/mock/5ca9efd1646ec411e7a920cc/one_test/line_chart_group3', {params})

        // response.data 是接口返回的json数据（已自动转换为json对象）
        const {status, data: chartData} = response.data

        if (status === 0) {
            this.setState({
                chartData
            })
        }
    }


    getRelativeTimes(times) {
        if (!times.length) {
            return []
        }
        const baseTime = new Date(times[0]).getTime()
        return times.map(t => {
            return Math.round((new Date(t).getTime() - baseTime) / 1000 / 60)
        })
    }

    // echart 文档 https://echarts.baidu.com/
    getChartProps(chartData) {
        const {jobName, computer: computerList = []} = chartData;
        // 解析图表数据格式
        const chartProps = {
            title: {
                text: jobName
            },
            legend: {
                data: []
            },
            xAxis: {
                data: [],
            },
            series: []
        }

        const sumInstances = computerList.reduce((sumInstances, computer, computerIndex) => {
            const {ip, instances} = computer
            if (sumInstances.length < instances.length) {
                sumInstances.length = instances.length
            }
            instances.forEach((instance, instanceIndex) => {
                const sumInstancesItem = sumInstances[instanceIndex] = sumInstances[instanceIndex] || {time: instance.time}

                void ['cpuPercent', 'virtualMemoryPercent', 'swapPercent'].forEach(key => {
                    let value = instance[key]
                    if (typeof instance[key] === 'object') {
                        value = Object.values(value).reduce((sum, val) => {
                            sum += parseFloat(val)
                            return sum
                        }, 0) / (Object.values(value).length)
                    } else {
                        value = parseFloat(value)
                    }
                    sumInstancesItem[key] = (sumInstancesItem[key] || 0) + (value / computerList.length)
                })
            })
            return sumInstances;
        }, [])

        console.log('sumInstances', sumInstances)

        void ['cpuPercent', 'virtualMemoryPercent', 'swapPercent'].forEach((key, index) => {
            // 图例数组
            chartProps.legend.data.push(key)
            if (index === 0) {
                // 横坐标数据
                chartProps.xAxis.data = this.getRelativeTimes(sumInstances.map(i => i.time))
            }
            // 图例纵坐标数据
            chartProps.series.push({
                name: key,
                type: 'line',
                data: sumInstances.map(i => {
                    return i[key].toFixed(1)
                })
            })
        })
        return chartProps
    }

    // echart 文档 https://echarts.baidu.com/
    getChartLedarProps(chartData) {
        const {jobName, computer: computerList = []} = chartData;
        // 解析图表数据格式
        const chartProps = {
            title: {
                text: jobName
            },
            legend: {
                data: []
            },
            xAxis: {
                data: [],
            },
            series: []
        }

        const KEYS = ['cpuPercent', 'virtualMemoryPercent', 'swapPercent', 'networkSentBytes', 'diskReadBytes']
        const sumInstances = computerList.reduce((sumInstances, computer, computerIndex) => {
            const {ip, instances} = computer
            if (sumInstances.length < instances.length) {
                sumInstances.length = instances.length
            }
            instances.forEach((instance, instanceIndex) => {
                const sumInstancesItem = sumInstances[instanceIndex] = sumInstances[instanceIndex] || {time: instance.time}

                void KEYS.forEach(key => {
                    let value = instance[key]
                    if (typeof instance[key] === 'object') {
                        value = Object.values(value).reduce((sum, val) => {
                            sum += parseFloat(val)
                            return sum
                        }, 0) / (Object.values(value).length)
                    } else {
                        value = parseFloat(value)
                    }
                    sumInstancesItem[key] = (sumInstancesItem[key] || 0) + (value / computerList.length)
                })
            })
            return sumInstances;
        }, [])

        console.log('sumInstances', sumInstances)

        const result = {}

        void KEYS.forEach((key, index) => {
            sumInstances.forEach((instance, instanceIndex) => {
                result[key] = (result[key] || 0) + (instance[key] / sumInstances.length)
            })
            if (sumInstances.length) {
                chartProps.series.push(parseInt(result[key]))
            }
        })


        return chartProps
    }

    getArrayChartProps(chartData, filter) {
        const {jobName, computer: computerList = []} = chartData
        // 取出选中的实例
        const instances = computerList[this.state.selectType].instances || []
        // 解析图表数据格式
        const chartProps = {
            title: {
                text: jobName
            },
            legend: {
                type: 'scroll',
                orient: 'horizontal',
                left: 10,
                top: 20,
                // show: false,
                // selectedMode: false,
                data: []
            },
            grid: {
                right: 70,
            },
            xAxis: {
                data: [],
            },
            series: []
        }
        if (instances.length) {
            let firstValue = instances[0][filter.name]
            const keys = Object.keys(firstValue)
            chartProps.xAxis.data = this.getRelativeTimes(instances.map(i => i.time))

            keys.forEach((key, index) => {
                let legend = '' + key
                chartProps.legend.data.push(key)
                chartProps.series.push({
                    name: legend,
                    type: 'line',
                    data: instances.map((instance, indexI) => {
                        return instance[filter.name][key]
                    }).filter(i => i !== undefined)
                })
            });
        }
        console.log('chartProps:', chartProps)
        return chartProps
    }


    onFilterChange(event) {
        let selectFilterIndex = +event.target.value
        const updateState = {
            selectFilterIndex
        }
        const filter = this.filters[selectFilterIndex]
        if (filter.type === 'array') {
            Object.assign(updateState, {
                selectType: 0
            })
        }
        this.setState(updateState);
    }

    render() {
        const {selectFilterIndex, chartData, jobIds} = this.state
        let chartProps
        const filter = this.filters[selectFilterIndex]
        let typeList = null
        if (chartData) {
            const {computer: computerList = []} = this.state.chartData
            if (filter.type === 'array') {
                typeList = computerList.map(i => i.ip)
            }
            chartProps = this.getChartProps(chartData, filter);
        }
        const chartLedarProps = this.getChartLedarProps(chartData)
        const infoList = [
            {
                value: chartData.jobId,
                title: '应用名称',
            },
            {
                value: 'cuihuanyu01lk',
                title: '应用名称',
            },
            {
                value: 'cuihuanyu01lk',
                title: '应用名称',
            },
            {
                value: 'cuihuanyu01lk',
                title: '应用名称',
            },
        ]
        return (
            <div className="App">
                <Box className="form">
                    <div className="form-item">
                        <span className="form-item-label">选择作业</span>
                        <select defaultValue={this.jobIdIndex} onChange={e => {
                            this.jobIdIndex = e.target.value
                        }}>
                            {jobIds.map((jobId, index) => <option key={index}
                                                                  value={index}>{jobId}</option>)}
                        </select>
                    </div>
                    <div className="form-item">
                        <span className="form-item-label">数量</span>
                        <input type="text" defaultValue={this.part} placeholder="数量" onChange={e => {
                            this.part = e.target.value
                        }}/>
                    </div>
                    <div className="form-item">
                        <button onClick={() => {
                            this.fetchLineChartData()
                        }}>查询
                        </button>
                    </div>
                </Box>
                <Box title="功耗信息详情">
                    <InfoList list={infoList}/>
                </Box>
                <Box title="实际性能曲线图">
                    <div className="line-chart-box">
                        {chartProps && <LineChart className={typeList ? 'line-chart-array' : ''} {...chartProps} />}
                    </div>
                    <div className="line-chart-box">
                        {chartProps &&
                        <LadarChart className={typeList ? 'line-chart-array' : ''} {...chartLedarProps} />}
                    </div>
                </Box>
            </div>
        );
    }
}

export default PageHome
